package com.gorio.lms.controller;

import com.gorio.lms.entities.*;
import com.gorio.lms.mapper.*;
import com.gorio.lms.service.ClientSocket;
import com.gorio.lms.tools.MyLoggerFactory;
import com.gorio.lms.tools.QRCodeGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static java.sql.Types.NULL;

@Controller
public class BookController {

    static Logger logger = MyLoggerFactory.getLogger(BookController.class);

    @Autowired
    BookInfoMapper bookInfoMapper;

    @Autowired
    BookEntityMapper bookEntityMapper;

    @Autowired
    ChineseLibraryClassificationMapper chineseLibraryClassificationMapper;

    @Autowired
    BooklibraryMapper booklibraryMapper;

    @Autowired
    PersonEntityMapper personEntityMapper;

//    //从isbn到中图分类号
//    @Autowired
//    ClientSocket clientSocket;

    /*
    TODO
    */
    @GetMapping("/books")
    public String list(Model model){
//        System.out.println("books");
        List<BookInfo> list = bookInfoMapper.getAllBook();
        model.addAttribute("emps",list);
        return "book/list";
    }

    @GetMapping("/book/{id}")
    public String moreInfo(@PathVariable("id") Integer id, Model model){
        id = Integer.valueOf(id);
        BookInfo bookInfo = bookInfoMapper.findById(id);
        if (bookInfo == null){
            logger.error("no such book");
            return "redirect:/books";
        }
        model.addAttribute("emp",bookInfo);
        return "book/add";

    }
    @GetMapping("/book")
    public String addBook(Model model) { return "book/add"; }

    /*add BookInfo*/
    @PostMapping("/book")
    public String addBookInfo(BookInfoTemp bookInfoTemp, Map<String, Object> map) {
        logger.info("保存的书籍信息：{}", bookInfoTemp);
        System.out.println("bookInfoTemp:");
        System.out.println(bookInfoTemp);
        if (!checkBookInfo(bookInfoTemp, map)) {
            return "redirect:/books";
        }
        //System.out.println("------");
        String chinese = bookInfoTemp.getBookRecommend();
        ChineseLibraryClassification chineseLibraryClassification = chineseLibraryClassificationMapper.selectByCode(chinese);

        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookName(bookInfoTemp.getBookName());
        bookInfo.setBookAuthor(bookInfoTemp.getBookAuthor());
        bookInfo.setBookPrinter(bookInfoTemp.getBookPrinter());
        bookInfo.setBookVersion(bookInfoTemp.getBookVersion());
        bookInfo.setBookPrinterVersion(bookInfoTemp.getBookPrinterVersion());
        bookInfo.setBookCover(bookInfoTemp.getBookCover());
        bookInfo.setBookIsbn(bookInfoTemp.getBookIsbn());
        bookInfo.setBookPrice(bookInfoTemp.getBookPrice());
        bookInfo.setBookRecommend(chineseLibraryClassification);
        bookInfo.setBookAbstract(bookInfoTemp.getBookAbstract());

        bookInfoMapper.addBookInfo(bookInfo);
        return "redirect:/books";
    }

//    @ResponseBody
    @GetMapping("/bookinfo/{id}")
    public String getBookInfo(@PathVariable("id") Integer id,Model model) {
//        BookInfo info = new BookInfo();

        BookEntity bookEntity = new BookEntity();
        bookEntity = bookEntityMapper.findByBookEntitiesId(id);
        //search
        model.addAttribute("emp",bookEntity);
        return "entity/bookinfolist";
//        return bookEntity.toString();
    }

    private Boolean checkBookInfo(BookInfoTemp bookInfoTemp, Map<String, Object> map) {
        return true;
    }

    /*add BookEntity*/
    @GetMapping("/entity")
    public String addEntity(Model model) { return "entity/add_xw"; }

//    @PostMapping("/entity")
//    public String addBookEntity(BookEntityTemp bookEntityTemp, Map<String, Object> map) {
//        logger.info("保存的书籍实体信息：{}", bookEntityTemp);
//        System.out.println("bookentity:"+bookEntityTemp);
//        System.out.println("bookowner:"+bookEntityTemp.getOwner());
//        if (!checkBookEntity(bookEntityTemp, map)) {
//            return "redirect:/entities";
//        }
//
//        BookEntity bookEntity = new BookEntity();
//
//        //填充PersonEntity
//        PersonEntity personEntity = new PersonEntity();
//        personEntity = bookEntityMapper.findPersonByStudentId(bookEntityTemp.getOwner());
//        bookEntity.setBookOwner(personEntity);
//
//        BookInfo bookInfo = new BookInfo();
//        bookInfo = bookEntityMapper.findBookInfoBtIsbn(bookEntityTemp.getISBN());
////        System.out.println("!!bookInfo:"+bookInfo);
//        bookEntity.setBookType(bookInfo);
//        bookEntity.setBookStatus(0);
//        bookEntity.setBookLocation(bookEntityTemp.getLocation());
////        System.out.println("**bookEntity:"+bookEntity);
//        bookEntityMapper.addBookEntities(bookEntity);
//        return "redirect:/entities";
//    }

    /**
     * TODO
     * @author xiawei
     * @description:
     * 1、数据库中的booklibrary书籍信息不全，若添加的书不在该表中，拟采用下列方式的一种：
     * （1）使用爬虫等其他程序返回对应的信息，并将其插入数据库中；
     * （2）跳转手动添加界面，添加之后将其信息插入booklibrary/bookinfo
     * 2、chinese_library_classification的信息与当前市面上的中图分类号部分无法对应，
     * 表现为图书中图分类号可能在chinese_library_classification中code的下一级（缺失），可能是网站问题（网站中也缺失）
     * 3、异常处理
     * 在该部分有很多数据库查询语句，对于查询结果不是预期结果没有做异常处理；
     * 4、缺少跳转手动添加界面；以及原目的是将该controller作为书籍实体添加的中间界面,即展示通过自动填充信息后的全部信息（过程），如书籍、拥有者，
     * 当添加者确认信息无误之后进行添加，但是现在是在该界面进行直接提交，仅展示结果，无法进行修改
     * 5、过多的处理函数拥挤在controller中，将信息处理过程封装到service中
     * 6、前端页面提交书籍，AllInfoOfBook无法接收isbn这一项信息。----------------important
     *7、注意service.ClientSocket中的端口号，如果爬虫在本地运行则为文件中所说，否则应更改为云服务器的IP和port
     *
     * */

    @PostMapping("/entity")
    public String addBookEntity(AllInfoOfBook allInfoOfBook,Model model ,Map<String,Object> map) throws IOException {
        System.out.println("--------------------------has executed!!!");
        allInfoOfBook.setIsbn("9787111558071");
        PersonEntity personEntity = new PersonEntity();
        String isbn = allInfoOfBook.getIsbn();
        //TODO 抽象为处理函数--xiawei
        BookInfo bookInfo = new BookInfo();
        ChineseLibraryClassification classify = new ChineseLibraryClassification();
        BookEntity bookEntity = new BookEntity();
        int bookEntityId;
        System.out.println(allInfoOfBook.toString());
        System.out.println(bookInfoMapper.getCountOfIsbn(isbn));
        if (bookInfoMapper.getCountOfIsbn(isbn)==0){
            System.out.println("break at 1");
            Booklibrary booklib = booklibraryMapper.selectByIsbn(isbn);
            System.out.println(booklib.getClassifId()+" break at 1.1");
            String type ;
            //得到分类号和分类id，并填入booklib中，其中的分类id就是info中的上架推荐id，填满booklib，然后对bookinfo进行填充
            if (booklib.getClassifId() == null){
                //得到isbn对应的分类号
                System.out.println(booklib.getClassifyType()+ " break at 2");
                if (booklib.getClassifyType()==null){
                    type =  ClientSocket.run(isbn);
                    booklib.setClassifyType(type);
                    System.out.println(type + " break at 2.1");
                }
                else {
                    type = booklib.getClassifyType();
                    System.out.println("break at 3");
                }
                //得到类型之后查分类表,得到对应isbn的id，将id进行更新
                if(type != null){
                    classify = chineseLibraryClassificationMapper.selectByCode(type);
                    System.out.println("break at 4");
                    System.out.println(classify.toString());
                }
                //更新表
                System.out.println(classify.getId());
                if (classify.getId() != null){
                    booklib.setClassifId(classify.getId());
                    booklibraryMapper.updateByClassifyType(type, isbn, classify.getId());
                    System.out.println("break at 5");
                }
            }
            else {
                classify = chineseLibraryClassificationMapper.selectByCode(booklib.getClassifyType());
                System.out.println("break at 6");
            }
            bookInfo.setBookName(booklib.getName());
            bookInfo.setBookAuthor(booklib.getAuthor());
            bookInfo.setBookPrinter(booklib.getPublisher());
            bookInfo.setBookVersion("1");
            bookInfo.setBookPrinterVersion("1");
            bookInfo.setBookCover(booklib.getHeadpic());
            bookInfo.setBookIsbn(isbn);
            bookInfo.setBookPrice(Double.parseDouble(booklib.getPrice()));
            bookInfo.setBookInboundNumber(1);
            bookInfo.setBookRecommend(classify);
            bookInfo.setBookAbstract(booklib.getMemo());
            bookInfoMapper.addBookInfo(bookInfo);
            bookInfo.setId(bookInfoMapper.getIdByIsbn(isbn));
            System.out.println("break at 7");
        }
        else {//如果bookinfo已经存在，则仅需要查询其id即可，但是中间页面，需要显示相关信息
            bookInfo = bookInfoMapper.getInfoByIsbn(isbn);
            System.out.println("break at 8");
        }
        //bookinfo结束，接下来是people
        personEntity = personEntityMapper.selectByStudentId(allInfoOfBook.getOwner());
        System.out.println("break at 9");
        //插入bookEntity
        bookEntity.setBookType(bookInfo);
        bookEntity.setBookOwner(personEntity);
        bookEntity.setBookStatus(allInfoOfBook.getStatus());
        bookEntity.setBookLocation(allInfoOfBook.getLocation());
        bookEntityMapper.addBookEntities(bookEntity);
        System.out.println("break at 10");
        //@fixme model是否可以携带多个数据？---xiawei
        model.addAttribute("info",bookInfo);
        model.addAttribute("allinfo",allInfoOfBook);
        model.addAttribute("owner",personEntity);
        model.addAttribute("recommend",classify);
        System.out.println("break at 11");
        //TODO 添加跳转按钮---xiawei
        return "entity/listall";
    }

    private Boolean checkBookEntity(BookEntityTemp bookEntityTemp, Map<String, Object> map) {
        return true;
    }


    @GetMapping("/entities")
    public String entitieslist(Model model){
        List<BookEntity> list = bookEntityMapper.findAllEntities();
//        System.out.println("entity:"+list);
        model.addAttribute("emps",list);
//        int num = bookEntityMapper.getBookCount();
//        System.out.println("num$$$"+num);
        return "entity/list";
    }

    @GetMapping("/entities/{studentId}")
    public String moreEntities(@PathVariable("studentId") String studentId, Model model){
        List<BookEntity> list= bookEntityMapper.findBystudentId(studentId);
        System.out.println("list person:"+list);
        if (list == null){
            logger.error("no such book");
            return "redirect:/entities";
        }
        model.addAttribute("emps",list);
        return "entity/infolist";

    }

    @GetMapping("/entity/{bookId}")
    public String moreEntitiesID(@PathVariable("bookId") Integer bookId, Model model){
        bookId = Integer.valueOf(bookId);
        BookInfo bookInfo = bookInfoMapper.findById(bookId);
        if (bookInfo == null){
            logger.error("no such book");
            return "redirect:/books";
        }
        model.addAttribute("emp",bookInfo);
        return "book/add";

    }

    @ResponseBody
    @GetMapping("/123")
    public String getBookNum(){
        List<BookEntity> list= bookEntityMapper.findAllEntities();
        int length = list.size();
        System.out.println("length:"+length);
        for(int i=0;i<length;i++)
        {
            System.out.println("int i="+i);
            QRCodeGenerator.creatQRS(list.get(i).getBookId());
        }
        return "success!";
    }
}
